﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static B.MESUI.Login.WareHouseDefinitionForm;
using static B.MESUI.Login.WareHouseManage.UpdateWareHouseDefinitionForm;
using static B.MESUI.Login.WareHouseManage.WareHouseArea.CreateAreaForm;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;

namespace B.MESUI.Login.WareHouseManage.WareHouseArea
{
    public partial class WareHouseAreaForm : DevExpress.XtraEditors.XtraForm
    {
        public WareHouseAreaForm()
        {
            InitializeComponent();
        }

        private void CreateArea_Click(object sender, EventArgs e)
        {
            CreateAreaForm createAreaForm = new CreateAreaForm();
            createAreaForm.ShowDialog();
        }
        public class ApiResult
        {
            public List<WarehouseModel> ResultData { get; set; }
        }
        public class AreaModel
        {
            /// <summary>
            /// Desc:唯一编码
            /// Default:
            /// Nullable:False
            /// </summary>           
            public string ID { get; set; }

            /// <summary>
            /// Desc:创建时间
            /// Default:
            /// Nullable:False
            /// </summary>           
            public DateTime CREATETIME { get; set; }

            /// <summary>
            /// Desc:更新时间
            /// Default:
            /// Nullable:True
            /// </summary>           
            public DateTime? UPDATETIME { get; set; }



            /// <summary>
            /// Desc:区域编码
            /// Default:
            /// Nullable:False
            /// </summary>           
            public string AREAID { get; set; }

            /// <summary>
            /// Desc:区域名称
            /// Default:
            /// Nullable:False
            /// </summary>           
            public string AREANAME { get; set; }
            public string WAREHOUSEID { get; set; }
            public string WAREHOUSENAME { get; set; }

            /// <summary>
            /// Desc:区域描述
            /// Default:
            /// Nullable:False
            /// </summary>           
            public string AREADESC { get; set; }
        }
        private async void GetAreaList_Load(object sender, EventArgs e)
        {
            await LoadDataFromApi();

            // 获取 GridView
            var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;

            // 假设 gridView1 是 gridControl1 的主视图
            gridView.OptionsSelection.MultiSelect = true;
            gridView.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
            gridView.OptionsSelection.ShowCheckBoxSelectorInGroupRow = DevExpress.Utils.DefaultBoolean.True;
            LoadWarehousesAsync();
        }
        private async Task LoadWarehousesAsync()
        {
            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.GetAsync("http://39.103.49.30:9981/api/WareHouseDefinition/GetWarehouseDefinitionIdAndName");

                    if (response.IsSuccessStatusCode)
                    {
                        string json = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResult>(json);

                        // 绑定数据到 GridLookUpEdit
                        gridLookUpEdit2.Properties.DataSource = result.ResultData;
                        gridLookUpEdit2.Properties.ValueMember = "Id";
                        gridLookUpEdit2.Properties.DisplayMember = "WareHouseName";

                        // 配置视图 - 这是关键修复点！
                        // 获取或创建 GridView
                        GridView view = gridLookUpEdit2.Properties.View as GridView;
                        if (view == null)
                        {
                            view = new GridView();
                            gridLookUpEdit2.Properties.View = view;
                        }

                        // 清除现有列
                        view.Columns.Clear();

                        // 添加列：仓库名称
                        view.Columns.Add(new GridColumn()
                        {
                            FieldName = "WareHouseName",
                            Caption = "仓库名称",
                            Visible = true
                        });

                        // 添加列：仓库ID（可选）
                        view.Columns.Add(new GridColumn()
                        {
                            FieldName = "Id",
                            Caption = "仓库ID",
                            Visible = false // 隐藏ID列
                        });

                        // 设置最佳列宽
                        view.BestFitColumns();

                        // 默认选中第一个
                        if (result.ResultData.Count > 0)
                            gridLookUpEdit2.EditValue = null;
                    }
                    else
                    {
                        MessageBox.Show("无法加载仓库信息");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
            }
        }
        public async Task LoadDataFromApi()
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    string url = "http://39.103.49.30:9981/api/Area/GetAREAMODEL?PageIndex=1&PageSize=10";
                    HttpResponseMessage response = await client.GetAsync(url);

                    if (response.IsSuccessStatusCode)
                    {
                        string jsonResponse = await response.Content.ReadAsStringAsync();

                        // 解析 JSON 数据
                        dynamic result = JsonConvert.DeserializeObject(jsonResponse);

                        // 假设 pagedatas 是一个包含数据的数组
                        var pagedatas = result.pageDatas;

                        // 将 pagedatas 转换为 List<AreaModel>
                        List<AreaModel> areaList = JsonConvert.DeserializeObject<List<AreaModel>>(pagedatas.ToString());

                        // 绑定数据到 GridControl
                        gridControl1.DataSource = areaList;
                    }
                    else
                    {
                        MessageBox.Show("API 请求失败");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
            }
        }
        
        private async void DeleteArea_Click(object sender, EventArgs e)
        {
            // 获取所有选中的行
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                MessageBox.Show("请选择要删除的信息！");
                return;
            }

            // 确认删除
            if (MessageBox.Show("确定要删除选中的信息吗？", "提示", MessageBoxButtons.YesNo) != DialogResult.Yes)
                return;

            foreach (var rowHandle in selectedRows)
            {
                var rowData = gridView1.GetRow(rowHandle) as AreaModel;
                if (rowData != null)
                {
                    // 假设后端API为 DELETE http://localhost:5031/api/WareHouseDefinition/Delete/{id}
                    string apiUrl = $"http://39.103.49.30:9981/api/Area/DeleteAREAMODEL?id={rowData.ID}";
                    using (HttpClient client = new HttpClient())
                    {
                        var emptyContent = new StringContent("", Encoding.UTF8, "application/json");
                        var response = await client.PostAsync(apiUrl, emptyContent);
                        if (!response.IsSuccessStatusCode)
                        {
                            MessageBox.Show($"删除ID为{rowData.ID}的数据失败！");
                        }
                    }
                }
            }

            // 删除后刷新列表
            await LoadDataFromApi();
        }
        public class WareHouseAreaEditModel
        {
            public string id { get; set; }
            public string areaid { get; set; }
            public string areaname { get; set; }
            public string warehouseid { get; set; }
            public string areadesc { get; set; }
        }
        
        private async void EditArea_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();

            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("还没有选中要编辑的数据");
                return;
            }

            if (selectedRows.Length > 1)
            {
                XtraMessageBox.Show("无法一次编辑多条数据");
                return;
            }

            // 只选中了一行，开始编辑
            var rowData = gridView1.GetRow(selectedRows[0]) as AreaModel;
            if (rowData == null)
            {
                XtraMessageBox.Show("获取数据失败");
                return;
            }

            string apiUrl = $"http://39.103.49.30:9981/api/Area/GetAREADESC?id={rowData.ID}";
            using (var client = new HttpClient())
            {
                var response = await client.GetAsync(apiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();

                    // 解析包含 ResultData 的响应
                    var resultWrapper = JsonConvert.DeserializeObject<ApiResult<WareHouseAreaEditModel>>(json);

                    if (resultWrapper != null && resultWrapper.ResultData != null)
                    {
                        var editModel = resultWrapper.ResultData;

                        // 打开编辑窗口并传入数据
                        var editForm = new UpdateAreaForm();
                        editForm.SetEditData(editModel);

                        if (editForm.ShowDialog() == DialogResult.OK)
                        {
                            // 刷新列表
                            await LoadDataFromApi();
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("获取的数据格式不正确");
                    }
                }
                else
                {
                    XtraMessageBox.Show("获取编辑数据失败");
                }
            }
        }

        private void ClearIf_Click(object sender, EventArgs e)
        {
            textEdit1.Text = string.Empty; // 清空区域编码
            textEdit2.Text = string.Empty; // 清空区域描述
            gridLookUpEdit2.Text = string.Empty; // 清空仓库下拉框
        }
        public class WareHouseAreaApiResult
        {
            public List<AreaModel> PageDatas { get; set; }
            public int Total { get; set; }
        }
        private async void SearchArea_Click(object sender, EventArgs e)
        {
            try
            {
                // 收集查询条件
                string areaid = this.textEdit1.Text.Trim();
                string areaname = this.textEdit2.Text.Trim();
                string warehouseid = gridLookUpEdit2.EditValue?.ToString();
                // 构建查询URL
                string apiUrl = "http://39.103.49.30:9981/api/Area/GetAREAMODEL?";

                // 添加分页参数
                apiUrl += "PageIndex=1&PageSize=10";

                // 添加查询条件参数（不为空时才添加）
                if (!string.IsNullOrWhiteSpace(areaid))
                    apiUrl += $"&AREAID={Uri.EscapeDataString(areaid)}";

                if (!string.IsNullOrWhiteSpace(areaname))
                    apiUrl += $"&AREANAME={Uri.EscapeDataString(areaname)}";

                if (!string.IsNullOrWhiteSpace(warehouseid))
                    apiUrl += $"&WAREHOUSEID={Uri.EscapeDataString(warehouseid)}";

                // 调用API获取数据
                using (HttpClient client = new HttpClient())
                {
                    var response = await client.GetAsync(apiUrl);
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<WareHouseAreaApiResult>(json);

                        if (result != null && result.PageDatas != null)
                        {
                            gridControl1.DataSource = result.PageDatas;
                            XtraMessageBox.Show($"查询到 {result.PageDatas.Count} 条记录");
                        }
                        else
                        {
                            gridControl1.DataSource = null;
                            XtraMessageBox.Show("未查询到匹配的记录");
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show($"查询失败: {response.StatusCode}");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"查询发生异常: {ex.Message}");
            }
        }
    }
}